package com.feeyo.groundservice.ws.utils

import android.content.pm.ApplicationInfo
import android.util.Log
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.Utils
import org.json.JSONArray
import org.json.JSONObject

/**
 * ClassName: FyLog <br></br>
 * Function: 该类封装了打印日志功能，并且根据AndroidManifest.xml中的application的
 * android:debuggable属性值设置是否开启打印日志功能。android:debuggable=true时, 开启打印
 * 功能,android:debuggable=false时,关闭打印功能。<br></br>
 *
 *
 * 打印同Log类一样分不同打印级别. date: 2014-2-12 下午11:38:54 <br></br>
 */
internal object FyLog {

    private const val FY_TAG = "fy"
    private const val MAX_LOG_LENGTH = 3 * 1024

    fun i(tag: String?, msg: String?) {
        if (isDebuggable) {
            Log.i(tag, msg ?: "null")
        }
    }

    fun v(tag: String?, msg: String?) {
        if (isDebuggable) {
            Log.v(tag, msg ?: "null")
        }
    }

    fun d(tag: String?, msg: String?) {
        if (isDebuggable) {
            Log.d(tag, msg ?: "null")
        }
    }

    fun w(tag: String?, msg: String?) {
        if (isDebuggable) {
            Log.w(tag, msg ?: "null")
        }
    }

    fun e(tag: String?, msg: String?) {
        if (isDebuggable) {
            Log.e(tag, msg ?: "null")
        }
    }

    fun fy(msg: String?) {
        i(FY_TAG, msg)
    }

    fun println(msg: String?) {
        if (isDebuggable) {
            kotlin.io.println(msg)
        }
    }

    fun json(tag: String, obj: Any?) {
        if (isDebuggable) {
            largeLog(tag, 1, json2String(GsonUtils.toJson(obj)))
        }
    }

    fun json(tag: String, jsonStr: String) {
        if (isDebuggable) {
            largeLog(tag, 1, json2String(jsonStr))
        }
    }

    private fun json2String(jsonStr: String): String {
        try {
            if (jsonStr.startsWith("{")) {
                return JSONObject(jsonStr).toString(2)
            } else if (jsonStr.startsWith("[")) {
                return JSONArray(jsonStr).toString(2)
            }
        } catch (e: Exception) {
        }
        return jsonStr
    }

    /**
     *
     * @param tag
     * @param index start with 1
     * @param msg
     */
    fun largeLog(tag: String, index: Int, msg: String) {
        var msg = msg
        if (!isDebuggable) {
            return
        }
        val fTag = tag + "_" + index
        if (msg.length < MAX_LOG_LENGTH) {
            Log.i(fTag, msg)
        } else {
            while (msg.length > MAX_LOG_LENGTH) {
                val log = msg.substring(0, MAX_LOG_LENGTH)
                msg = msg.replace(log, "")
                Log.i(fTag, log)
            }
            Log.i(fTag, msg)
        }
    }

    private val isDebuggable: Boolean
         get() {
             val appInfo = Utils.getApp().applicationInfo
             return appInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
         }
}
